using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Masters.Materials.Commands;

/// <summary>
/// 创建物料命令。
/// </summary>
public record CreateMaterialCommand(MdMaterialDto Material) : IRequest<IResult<bool>>;

internal sealed class CreateMaterialCommandHandler(IRepository<MdMaterial> repo) : IRequestHandler<CreateMaterialCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateMaterialCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.Code == request.Material.Code, cancellationToken))
        {
            return Result.Failure("物料编号已存在");
        }

        var material = request.Material.Adapt<MdMaterial>();

        // 确保规则项不为 null，可以为空集合。
        if (material.Rules != null)
        {
            material.Rules.RemoveAll(string.IsNullOrWhiteSpace);
        }
        else
        {
            material.Rules ??= [];
        }
        var ok = await repo.InsertAsync(material, cancellationToken);
        return Result.From(ok);
    }
}
